#include "LogCheck.h"

QScopedPointer<LogCheck> LogCheck::ms_instance;
LogCheck::LogCheck(QObject *parent): QThread(parent)
//   , m_timer(new QTimer(parent))
{
    m_logDirPath = QDir::rootPath() + s_logBaseFolderPath;
    // m_timer.data()->setInterval(s_checkIntervalMSec);
    // connect(m_timer.data(), &QTimer::timeout, this, &LogCheck::checkFile);
    // m_timer.data()->start();
}

LogCheck::~LogCheck()
{
}

void LogCheck::run()
{
    QTimer timer;
    timer.setInterval(s_checkIntervalMSec);
    connect(&timer, &QTimer::timeout, this, &LogCheck::checkFile);
    timer.start();
    checkFile();
    exec();
}

void LogCheck::checkFile()
{
    qDebug() << "enter checkFile";
    checkFileNum();
    checkFileSize();
}

void LogCheck::checkFileNum()
{
    qDebug() << "enter checkFileNum";
    QDir dir(m_logDirPath);
    if (!dir.exists()) {
        qDebug() << "dir=" << dir.path() << " no exist";
        return;
    }
    QStringList filterStrList;
    filterStrList << m_appName + "*";
    dir.setFilter(QDir::Files | QDir::NoSymLinks);
    dir.setNameFilters(filterStrList);
    dir.setSorting(QDir::Time);
    QFileInfoList fileInfoList = dir.entryInfoList();
    int32_t nowFileNum = fileInfoList.size();
    if (nowFileNum < s_maxFileNum) {
        return;
    }
    int32_t deleteFileNum = nowFileNum - s_maxFileNum;
    for (int32_t index = s_maxFileNum; index < nowFileNum; index++) {
        QFile tempFile(fileInfoList[index].absoluteFilePath());
        tempFile.remove();
    }
    qDebug() << "nowFileNum=" << nowFileNum << " maxFileNum=" << s_maxFileNum;
}

void LogCheck::checkFileSize()
{
    qDebug() << "checkFileSize";
    QDir dir(m_logDirPath);
    if (!dir.exists()) {
        qDebug() << "dir=" << dir.path() << " no exist";
        return;
    }
    QStringList filterStrList;
    filterStrList << m_appName + "*";
    dir.setFilter(QDir::Files | QDir::NoSymLinks);
    dir.setNameFilters(filterStrList);
    dir.setSorting(QDir::Time);
    QFileInfoList fileInfoList = dir.entryInfoList();
    foreach(const QFileInfo & tempFileInfo, fileInfoList)
    {
        qDebug() << "path=" << tempFileInfo.absoluteFilePath() << " size=" << tempFileInfo.size();
        if (tempFileInfo.size() > s_maxByteNum) {
            QFile tempFile(tempFileInfo.absoluteFilePath());
            tempFile.resize(0);
        }
    }
}

LogCheck *LogCheck::instance()
{
    if (ms_instance.isNull()) {
        ms_instance.reset(new LogCheck());
    }
    return ms_instance.data();
}

void LogCheck::doInit(const QString &strAppName)
{
    m_appName = strAppName.toLower();
    m_appName.replace(QRegExp("[^a-z0-9]"), "-");
    m_appName.replace(QRegExp("[-]+"), "-");
    m_appName.replace(QRegExp("^[^a-z]+"), "");
    m_appName.replace(QRegExp("[-]+$"), "");
    if (!isRunning()) {
        start();
    }
}

void LogCheck::init(const QString &strAppName)
{
    instance()->doInit(strAppName);
}
